package com.gyg.executorDemo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 创建线程方式3：实现Callable接口
 */
public class TestThread05 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建三个线程
        MyCallable myCallable1 = new MyCallable(100);
        MyCallable myCallable2 = new MyCallable(200);
        MyCallable myCallable3 = new MyCallable(300);

        //通过线程池提交线程并执行
        ExecutorService es = Executors.newFixedThreadPool(3);
        Future<String> f1 = es.submit(myCallable1);
        Future<String> f2 = es.submit(myCallable2);
        Future<String> f3 = es.submit(myCallable3);
        //通过get方法获取执行结果
        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());

        //关闭服务
        es.shutdown();
    }

}

/**
 * 实现Callable接口
 */
class MyCallable implements Callable<String> {
    private int n;

    public MyCallable(int n) {
        this.n = n;
    }

    /**
     * 重写call方法
     *
     * @return
     * @throws Exception
     */
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += i;
        }
        return Thread.currentThread().getName() + "获取结果：" + sum;
    }
}
